package com.example.netty.lengthfield.client;

import cn.hutool.core.util.ByteUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;

/**
 * <p></p>
 *
 * @author xin
 * @version 2023/11/2 16:41
 **/
public class LengthFieldClientHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(LengthFieldClientHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("接收到服务端的响应");

        String body = (String) msg;
        System.out.println("输出原始文件，有乱码："+body);
        byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
        System.out.println("输出长度" + ByteUtil.bytesToInt(new byte[]{bytes[0], bytes[1], bytes[2], bytes[3]}, ByteOrder.BIG_ENDIAN));
        byte[] msgBytes = new byte[bytes.length - 4];
        System.arraycopy(bytes, 4, msgBytes, 0, msgBytes.length);
        body = new String(msgBytes);
        System.out.println("-----去除长度client start------| \n " + body + " \n| ------client end------");
    }
}
